package com.bom_samaritano.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DataAdapter implements DAO<VOGeneric> {

	// private static DataAdapter dataAdapter;
	private SQLiteDatabase db;
	private DBHelper dbHelper = null;

	private DataAdapter(Context context) {
		dbHelper = new DBHelper(context);
		Person p = new Person();
		p.setName("Thiago Carvalho");
		p.setEmail("thiago.cmv@gmail.com");
		this.insert(p);
	}

	// public static DataAdapter getInstance(Context context) {
	// if (dataAdapter == null) {
	// dataAdapter = new DataAdapter(context);
	// }
	// return dataAdapter;
	// }

	@Override
	public void insert(VOGeneric vo) {

		ContentValues cv = new ContentValues();

		for (Map.Entry<String, Object> entry : vo.getMap().entrySet()) {

			cv.put(entry.getKey(), String.valueOf(entry.getValue()));
		}
		this.db = dbHelper.getWritableDatabase();
		this.db.insert(vo.TABLE, null, cv);
		this.db.close();

	}

	@Override
	public void update(VOGeneric vo, long id) {
		ContentValues cv = new ContentValues();

		for (Map.Entry<String, Object> entry : vo.getMap().entrySet()) {

			cv.put(entry.getKey(), String.valueOf(entry.getValue()));
		}
		this.db = dbHelper.getWritableDatabase();
		this.db.update(vo.TABLE, cv, "id = ",
				new String[] { String.valueOf(id) });
		this.db.close();

	}

	@Override
	public Collection<String> selectAll() {
		Collection<String> collection = new ArrayList<String>();
		Cursor cursor = this.db.query(Person.TABLE, new String[] {
				Person.COL_ID, Person.COL_NAME, Person.COL_EMAIL,
				Person.COL_PHONE, Person.COL_VACANCY, Person.COL_HAS_CAR },
				null, null, null, null, null);

		cursor.moveToFirst();

		while (!cursor.isAfterLast()) {
			Person person = new Person();
			person.setId(cursor.getInt(0));

			collection.add(person.toString());
			cursor.moveToNext();
		}

		// if (cursor.moveToFirst()) {
		// do {
		// collection.add(cursor.getString(0));
		// } while (cursor.moveToNext());
		// }
		// if (cursor != null && !cursor.isClosed()) {
		// cursor.close();
		// }
		return collection;

	}

	@Override
	public void delete(VOGeneric object) {
		// TODO Auto-generated method stub

	}

}